/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-03-09 19:04:50
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-10 13:50:47
 */

import { orderAPI } from "../../../../../api/index";
import {
  returnStatus,
  returnStatusToast,
  getPromise,
  UploadFile
} from '../../../../../utils/index'

var appInst =  getApp();


// pages/mine/order/afterOrder/pay&goods/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showReason: false,
    showAfterNum:false,
    waySwitch:[
      {
        title: '尺码拍错/不喜欢/不舒服/效果差',
        value:0
      }
    ],
    amountInfo:{},
    fileList:[],
    code:1,
    form:{
      "aftersaleQuantity": 1,
      "aftersaleType": 0,
      "images": [],
      "orderDetailId": 0,
      "reason": "",
      "refundAmount": 0,
      "remark": ""
    }
  },
  showNum(){
    this.setData({
      showAfterNum: true
    })
  },
  showReason(){
    this.setData({
      showReason: true
    })
  },
  hideReason(){
    this.setData({
      showReason:false
    })
  },
  onChangeNumber({detail}){
    this.setData({
      'form.aftersaleQuantity':detail
    })
  },
  
  // 删除图片
  onDelImage({
    detail
  }) {
    const {
      index
    } = detail
    const fileList = this.data.fileList
    fileList.splice(index, 1)
    this.setData({
      fileList,
      showError: fileList.length > 5
    })
  },
  handleImage({detail:{file}}){
    this.setData({fileList:[...this.data.fileList,...file]})
  },
  async onSubmit(){
    // 上传图片
    let images = []
    let files = []
    this.data.fileList.forEach(item=>{
      files.push(item.path)
    })
    if(files.length && !this.data.form.images.length){
      const _ = await UploadFile.upload(files, 'OTHER', (progress) => {})
      if (_ && _.length === files.length) {
        _.forEach((item, index) => {
          try {
            const res = JSON.parse(item)
            if (res.code === 200) {
              images.push(res.data)
            }
          } catch (error) {
            wx.showToast({
              title: '解析上传返回结果出错',
              icon: 'none',
              duration: 800,
            });
          } finally {
            wx.hideToast();
          }
        })
      }
    }
    this.setData({
      'form.images': images
    })
    // 判断字段
    const wait = this.data.form.refundAmount
    if(!/^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$/.test(wait)||wait>this.data.amountInfo.refundAmountLimit){
      wx.showToast({
        title: '金额输入不正确',
        icon: 'none',
        duration: 800,
      });
      return false
    }
    // 提交售后
    orderAPI.handleAfter(this.data.form).then(async res=>{
      returnStatusToast(res,()=>{
        wx.reLaunch({
          url: '/pages/mine/order/afterOrder/status/index?status=false&message=申请已经提交，正在等待客服审核请耐心等待…&title=申请成功',
        });
      })
    })
    console.log(this.data.form)
  },
  onChange({detail}){
    this.setData({
      'form.reason': detail
    })
  },
  onCellSelect({currentTarget:{dataset:{name}}}){
    this.setData({
      'form.reason': name
    })
  },
  inputChange({detail,target:{dataset:{type}}}){
    const temp = `form.${type}`
    this.setData({
      [temp]:detail
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('params',async  ({info,code,title})=>{
      this.setData({info,code})
     appInst.setTitle(title)
      // 获取售后理由
     const res = await orderAPI.queryAfterReason({
        reasonCode:code
      })
      const {reasons} = await returnStatus(res)
      if(reasons){
        this.setData({
          reasons
        })
      }
      const amountRes = await orderAPI.calcAmount({
        orderDetailId:info.orderDetailId,
        quantity:info.quantity
      })
      const amountInfo = await returnStatus(amountRes)
      this.setData({amountInfo,'form.aftersaleType': code,
      'form.orderDetailId':info.orderDetailId,})
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})